package org.sdkj.device.test.tcp.utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.ArrayList;

import org.sdkj.device.test.vein.utils.FeatureUtils;

/**
 * 数据包到达后处理该数据
 * 
 * @author lenovo
 *
 */
public class MessageHandle {
	@SuppressWarnings("unused")
	private Socket socket = null;
	@SuppressWarnings("unused")
	private InputStream in_s = null;
	private OutputStream out_s = null;

	public static MessageHandle getInstance(InputStream in_s, OutputStream out_s, Socket socket) {
		MessageHandle mhObj = new MessageHandle();
		mhObj.in_s = in_s;
		mhObj.out_s = out_s;
		mhObj.socket = socket;
		return mhObj;
	}

	public void handle(int cmd, byte[] recvBuf, int datalen) {
		if (cmd == 0x01) {
			// 收到心跳包
			System.out.println("bit。。。");
			return;
		}
		// System.out.println("-------------处理数据包------Start------------");
		switch (cmd) {
		default:
			break;
		case 0x0F://
			if (DemoState.state == 1) {
				try {
					// ########1.采集一条指静脉模板
					FeatureUtils.addFeature(recvBuf);
					// 模板计数
					DemoState.registerNum++;
					System.out.println("模板采集成功，第" + DemoState.registerNum + "次采集");
					MessageSender.getInstance(out_s).sayRePutFinger();
				} catch (Exception e) {
					MessageSender.getInstance(out_s).sayPutFingerRight();
					System.out.println("模板采集失败，请重新采集:" + e.getMessage());
				}
				if (DemoState.registerNum >= 3) {
					// ########2.采集完成合并特征
					try {
						FeatureUtils.mergeFeature();
						//DemoState.state = 2;
						MessageSender.getInstance(out_s).sayBookSuccess();
						System.out.println("融合成功！");
						//初始化计数器
						DemoState.registerNum=0;
						DemoState.features=new ArrayList<>();
						System.out.println("当前特征列表数:"+DemoState.features.size());
						//System.out.println("再次放入手指将进行验证!");
					} catch (Exception e) {
						DemoState.clear();
						MessageSender.getInstance(out_s).sayPutFinger();
						System.out.println("融合失败:" + e.getMessage());
					}
				}
				break;
			}
			if (DemoState.state == 2) {
				// ########3.验证
				try {
					int n = FeatureUtils.checkFeature(recvBuf);
					System.out.println("如果n不等于-1说明找到匹配的模板，n的数值代表匹配到的模板序数，验证结果：" + n);
					if (n < 0) {
						System.out.println("验证失败");
						MessageSender.getInstance(out_s).sayCheckFail();
					} else {
						DemoState.checkNum++;
						System.out.println("验证成功,第" + DemoState.checkNum + "次验证成功");
						MessageSender.getInstance(out_s).sayCheckSuccess();
					}
				} catch (Exception e) {
					System.out.println("验证失败," + e.getMessage());
					MessageSender.getInstance(out_s).sayCheckFail();
				}
			}
			break;
		}
		// System.out.println("-------------处理数据包------end--------------");
	}
}
